var AV = require("leanengine");
var moment = require('moment');
var _ = require('lodash');

var AVUtils = {
  toJSON: function(avo) {
    var json = avo.toJSON();

    for (var key in json) {
      var value = json[key];
      if (_.isArray(value)) {
        var ids = [];
        for ( var i in value) {
          var entity = value[i];
          if (_.isPlainObject(entity) && 'objectId' in entity) {
            ids.push(entity.objectId);
          }
        }
        if (ids.length == value.length) {
          json[key] = ids;
        }
      } else if (_.isPlainObject(value)) {
        if ('objectId' in value) {
          json[key] = value.objectId;
        }
      }
    }

    if (! ('id' in json)) {
      json.id = json.objectId;
      delete json.objectId;
    }
    if ('createdAt' in json) {
      json.createdAt = moment(json.createdAt).format('YYYY-MM-DD HH:mm:ss');
    }
    if ('updatedAt' in json) {
      json.updatedAt = moment(json.updatedAt).format('YYYY-MM-DD HH:mm:ss');
    }

    if ('KUser' == avo.className) {
      delete json.password;
    }

    return json;
  },
  /**
   * 将临时文件更改为已使用文件.
   * @param id
   */
  usingFile: function(id){
    // TODO update file make as used.
    /*
     var query = new AV.Query(AV.Object.extend('_File'));
     query.get(id, {
     success: function(file) {
     console.log(file);
     var metaData = file.get('metaData');
     if (metaData.kIsTemp) {
     metaData.kIsTemp = false;
     file.set('metaData', metaData);
     console.log(file);
     file.save().then(function(obj) {
     console.log('save success');
     }, function(error) {
     console.log('save error:');
     console.log(error);
     });
     }
     },
     error: function(object, error) {
     // ignore
     }
     });
     */
  },
  getFileUrlByName: function(name) {
    var promise = new AV.Promise();
    var query = new AV.Query(AV.Object.extend('_File'));
    query.equalTo("name", name);
    query.first({
      success: function(result) {
        promise.resolve(null != result ? result.get('url') : null);
      },
      error: function(error) {
        promise.resolve(null);
      }
    });
    return promise;
  }
}

module.exports = AVUtils;